package xyz.xcvu.ma2.module;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import xyz.xcvu.ma2.utils.MimeUtil;

import java.io.InputStream;

@Component
@MagicModule("oos")
public class Oos {
    private static final Log log = LogFactory.get();
    private String accessKey;
    private String secretKey;
    private String bucket;

    public String upload(
            InputStream inputStream,
            String path
    ){
        UploadManager uploadManager = new UploadManager(new Configuration(Region.huabei()));
        String uploadToken = Auth.create(accessKey, secretKey).uploadToken(bucket);
        path = path.startsWith("/") ? path.substring(1) : path;
        Response response;
        try {
            response = uploadManager.put(inputStream, path, uploadToken, null, MimeUtil.getMimeType(path));
        } catch (QiniuException e) {
            log.warn(e.getMessage());
            return "";
        }
        if (!response.isOK()) {
            return "";
        }
        return "/" + path;
    }

    public Oos setAccessKey(String str){
        this.accessKey = str;
        return this;
    }

    public Oos setSecretKey(String str){
        this.secretKey = str;
        return this;
    }

    public Oos setBucket(String str){
        this.bucket = str;
        return this;
    }
}
